﻿using System;
using LEDHelper;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using LEDDataBase;
using LEDShow;
using System.Threading;
using System.Windows;
namespace LEDManager
{
    /// <summary>
    /// Interaction logic for LEDConsole.xaml
    /// </summary>
    public partial class LEDConsole3 : Window
    {
        MainWindow fm = new MainWindow();
        SortedDictionary<string, LEDUnit3> ledList;
        public LEDData m_LED = new LEDData();
        LEDDataSet SetLED = new LEDDataSet();
        LEDDataSet SetLEDStatus = new LEDDataSet();
        DataTable tbLED = new DataTable();

        string fileplay = @"D:\SXDFile\InBoard.dat";
        bool IsFinished = false;
        public LEDConsole3()
        {

            XLED_Startup();
            m_LED.Reset();
            fm.Show();
            ledList = new SortedDictionary<string, LEDUnit3>();
            StartControl();
        }

        ~LEDConsole3()
        {
            XLED_Cleanup();
        }
        private void StartControl()
        {

            string filePath = Path.Combine(PathHelper.ApplicationPath, @"SXDFile");
            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }
            filePath = Path.Combine(PathHelper.ApplicationPath, @"SXDFile/Export");
            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }
            filePath = Path.Combine(PathHelper.ApplicationPath, @"SXDFile/Temp");
            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }

            DataSet setResult = new DataSet();
            setResult = m_LED.LoadLedData();
            SetLED = new LEDDataSet();
            foreach (DataTable tb in setResult.Tables)
            {
                SetLED.Merge(tb);
            }
            tbLED = SetLED.LEDLIST;
            LEDUnit3 led;
            string ledid = "";
            string expression = "";
            string system = "";
            string ledkey = "";
            ///初始化所有的LED
            foreach (DataRow dwLED in tbLED.Rows)
            {
                system = dwLED["LLSYSTEM"].ToString();
                ledid = dwLED["LLLEDID"].ToString();
                ledkey = system + ledid;
                expression = "";
                if (ledList.ContainsKey(ledkey))
                {
                    led = (LEDUnit3)ledList[ledkey];
                    led.SetUp(dwLED);
                }
                else
                {
                    led = new LEDUnit3();
                    led.m_LED = m_LED;
                    led.SetUp(dwLED);
                    ledList.Add(ledkey, led);
                }
                //AddTabItem(ledkey, led);
            }
            m_LED.SaveLocalData();
        }
        public void AddLED(Dictionary<string, string> LEDPara)
        {

            m_LED.AddLED(SetLED, LEDPara);
            m_LED.SaveLEDData(SetLED);

        }
        public string LEDGetIP(int nLEDID)
        {
            string result = "IP:屏幕尚未在系统内注册";
            string led = "";
            var query = from row in SetLED.LEDLIST.AsEnumerable()
                        where row["LLLEDID"].ToString() == nLEDID.ToString()
                        select row;
            foreach (DataRow row in query)
            {
                result = "IP:" + row["IPADDRESS"].ToString();
            }
            return result;
        }
        public string GetLEDList()
        {
            string result = "";
            string led = "";
            foreach (DataRow row in SetLED.LEDLIST.Rows)
            {
                /*
        
                dwLED["LLLEDID"] = nLEDID;
                dwLED["LLLEDPRE"] = LEDPara["LLLEDPRE"].ToString();
                dwLED["LLLEDNUMBER"] = LEDPara["LLLEDNUMBER"].ToString();
                dwLED["IPADDRESS"] = LEDPara["IPADDRESS"].ToString();
                dwLED["DEVTYPE"] = LEDPara["DEVTYPE"].ToString();
                dwLED["DSPEED"] = LEDPara["DSPEED"].ToString();
                dwLED["LOCPORT"] = LEDPara["LOCPORT"].ToString();
                dwLED["COMPORT"] = LEDPara["COMPORT"].ToString();
                dwLED["LLSCREENTYPE"] = LEDPara["LLSCREENTYPE"].ToString();
                dwLED["REMOTPORT"] = LEDPara["REMOTPORT"].ToString();*/
                led = "";
                led += "LEDID:" + row["LLLEDID"].ToString() + ";";
                led += "IP:" + row["IPADDRESS"].ToString() + ";";
                led += "devtyp:" + row["DEVTYPE"].ToString() + ";";
                led += "screentype:" + row["LLSCREENTYPE"].ToString() + ";";
                result += led + "*" + Environment.NewLine;
            }
            return result;
        }
        StringBuilder inf;
        public delegate int Compile(String command, StringBuilder inf);//编译
        public object PerformCommand(string command, object p1 = null, object p2 = null, object p3 = null, object p4 = null, object p5 = null, object p6 = null, object p7 = null, object p8 = null, object p9 = null, object p10 = null,
            object p11 = null, object p12 = null, object p13 = null, object p14 = null, object p15 = null, object p16 = null, object p17 = null, object p18 = null, object p19 = null, object p20 = null,
            object p21 = null, object p22 = null, object p23 = null, object p24 = null, object p25 = null, object p26 = null, object p27 = null, object p28 = null, object p29 = null, object p30 = null)
        {
            object result = -1;
            try
            {
                Int32 serverindex = 0;
                Int32 localport = 0;
                Int32 listaddr = 0;
                Int32 count = 0;
                Int32 itemindex = 0;
                Int32 width = 0;
                Int32 height = 0;
                string previewfile = "";
                Int32 iValue = 0;
                string szValue = "";

                switch (command)
                {
                    case "ResetLedData":
                        m_LED.ResetLedData();
                        break;
                    case "LED_Startup":
                        result = LED_Startup();
                        break;
                    case "LED_Cleanup":
                        result = LED_Cleanup();
                        break;
                    case "LED_GetPlayContent":
                        LEDUnit3 led = (LEDUnit3)p1;
                        fileplay = (string)p2;
                        LEDShow.TDeviceParam devp = new LEDShow.TDeviceParam();
                        devp.comFlow = led.sender.devParam.comFlow;
                        devp.comPort = led.sender.devParam.comPort;
                        devp.comSpeed = led.sender.devParam.comSpeed;
                        devp.devType = led.sender.devParam.devType;
                        devp.dstAddr = led.sender.devParam.dstAddr;
                        devp.key = led.sender.devParam.key;
                        devp.locPort = led.sender.devParam.locPort;
                        devp.pkpLength = led.sender.devParam.pkpLength;
                        devp.rmtHost = led.sender.devParam.rmtHost;
                        devp.rmtPort = led.sender.devParam.rmtPort;
                        devp.srcAddr = led.sender.devParam.srcAddr;
                        devp.txMovewin = led.sender.devParam.txMovewin;
                        devp.txRepeat = led.sender.devParam.txRepeat;
                        devp.txTimeo = led.sender.devParam.txTimeo;
                        //worker.RunWorkerAsync(devp);
                        if (System.IO.File.Exists(fileplay))
                        {
                            System.IO.File.Delete(fileplay);
                        }
                        fileplay = fm.LED_GetPlayContent(devp, fileplay);
                        //result=GetFileStream(fileplay);
                        //string fileplay = fm.GetContent(devp); 
                        break;
                    case "LED_PreviewFile":
                        LEDUnit3 ledx = (LEDUnit3)p1;
                        width = System.Convert.ToInt32(p2);
                        height = System.Convert.ToInt32(p3);
                        fileplay = (string)p4;
                        fm.LED_PreviewFile(width, height, fileplay);
                        break;
                    case "LED_GetScreenCopy":
                        fileplay = (string)p2;
                        result = fm.LED_GetScreenCopy(fileplay);
                        break; 
                    case "LED_Report_CreateServer":
                        serverindex = System.Convert.ToInt32(p1);
                        localport = System.Convert.ToInt32(p2);
                        LED_Report_CreateServer(serverindex, localport);
                        break;
                    case "LED_Report_RemoveServer":
                        serverindex = System.Convert.ToInt32(p1);
                        LED_Report_RemoveServer(serverindex);
                        break;
                    case "LED_Report_RemoveAllServer":
                        LED_Report_RemoveAllServer();
                        break;
                    case "LED_Report_GetOnlineList":
                        serverindex = System.Convert.ToInt32(p1);
                        listaddr = System.Convert.ToInt32(p2);
                        count = System.Convert.ToInt32(p3);
                        result = LED_Report_GetOnlineList(serverindex, listaddr, count);
                        break;
                    case "LED_Report_GetOnlineItemName":
                        serverindex = System.Convert.ToInt32(p1);
                        itemindex = System.Convert.ToInt32(p2);
                        result = LED_Report_GetOnlineItemName(serverindex, itemindex);
                        break;
                    case "LED_Report_GetOnlineItemHost":
                        // LED_Report_GetOnlineItemHost(Int32 serverindex, Int32 itemindex)
                        serverindex = System.Convert.ToInt32(p1);
                        itemindex = System.Convert.ToInt32(p2);
                        result = LED_Report_GetOnlineItemHost(serverindex, itemindex);
                        break;
                    case "LED_Report_GetOnlineItemPort":
                        //LED_Report_GetOnlineItemPort(Int32 serverindex, Int32 itemindex)
                        serverindex = System.Convert.ToInt32(p1);
                        itemindex = System.Convert.ToInt32(p2);
                        result = LED_Report_GetOnlineItemPort(serverindex, itemindex);
                        break;
                    case "LED_Report_GetOnlineItemAddr":
                        //object LED_Report_GetOnlineItemAddr(Int32 serverindex, Int32 itemindex)
                        serverindex = System.Convert.ToInt32(p1);
                        itemindex = System.Convert.ToInt32(p2);
                        result = LED_Report_GetOnlineItemAddr(serverindex, itemindex);
                        break;
                    //(int AValue)
                    case "LED_CloseDeviceOnTerminate":
                        int AValue = System.Convert.ToInt32(p1);
                        LED_CloseDeviceOnTerminate(AValue);
                        break;
                    case "LED_Cache_GetBoardParam_IP":
                        result = LED_Cache_GetBoardParam_IP();
                        break;
                    case "LED_Cache_GetBoardParam_Mac":
                        result = LED_Cache_GetBoardParam_Mac();
                        break;
                    case "LED_Cache_GetBoardParam_Addr":
                        result = LED_Cache_GetBoardParam_Addr();
                        break;
                    case "LED_Cache_GetBoardParam_Width":
                        result = LED_Cache_GetBoardParam_Addr();
                        break;
                    case "LED_Cache_GetBoardParam_Height":
                        result = LED_Cache_GetBoardParam_Height();
                        break;
                    case "LED_Cache_GetBoardParam_Brightness":
                        result = LED_Cache_GetBoardParam_Brightness();
                        break;
                    case "LED_Cache_SetBoardParam_IP":
                        szValue = System.Convert.ToString(p1);
                        LED_Cache_SetBoardParam_IP(szValue);
                        break;
                    case "LED_Cache_SetBoardParam_Mac":
                        szValue = System.Convert.ToString(p1);
                        LED_Cache_SetBoardParam_Mac(szValue);
                        break;
                    case "LED_Cache_SetBoardParam_Addr":
                        iValue = System.Convert.ToInt32(p1);
                        LED_Cache_SetBoardParam_Addr(iValue);
                        break;
                    case "LED_Cache_SetBoardParam_Width":
                        iValue = System.Convert.ToInt32(p1);
                        LED_Cache_SetBoardParam_Width(iValue);
                        break;
                    case "LED_Cache_SetBoardParam_Height":
                        iValue = System.Convert.ToInt32(p1);
                        LED_Cache_SetBoardParam_Height(iValue);
                        break;
                    case "LED_Cache_SetBoardParam_Brightness":
                        iValue = System.Convert.ToInt32(p1);
                        LED_Cache_SetBoardParam_Brightness(iValue);
                        break;
                    case "LED_Cache_SetBoardParam2":
                        //param_index = System.Convert.ToInt32(p1);
                        //LED_Cache_SetBoardParam2(param_index);
                        break;
                    case "LED_Registration":
                        Dictionary<string, string> ledp = new Dictionary<string, string>();
                        ledp.Add("LLSYSTEM", "000");
                        ledp.Add("LEDID", System.Convert.ToString(p1));
                        ledp.Add("LLLEDPRE", (string)p2);
                        ledp.Add("LLLEDNUMBER", (string)p3);
                        ledp.Add("MACADDRESS", (string)p4);
                        ledp.Add("IPADDRESS", (string)p5);
                        ledp.Add("RMTHOST", (string)p5);
                        ledp.Add("DEVTYPE", (string)p6);
                        ledp.Add("COMSPEED", (string)p7);
                        ledp.Add("DSPEED", (string)p7);
                        ledp.Add("LOCPORT", (string)p8);
                        ledp.Add("LOCALPORT", (string)p8);
                        ledp.Add("COMPORT", (string)p9);
                        ledp.Add("LLSCREENTYPE", (string)p10);
                        ledp.Add("RMTPORT", (string)p11);
                        ledp.Add("REMOTPORT", (string)p11);
                        ledp.Add("DSTADDR", (string)p12);
                        ledp.Add("WIDTH", (string)p13);
                        ledp.Add("HEIGHT", (string)p14);
                        ledp.Add("NEWDATE", (string)p15);
                        ledp.Add("NEWUSER", (string)p16);
                        ledp.Add("LASTDATE", (string)p17);
                        ledp.Add("LASTUSER", (string)p18);
                        AddLED(ledp);
                        StartControl();
                        result = 0;
                        break;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                result = "-1";
            }
            return result;
        }

        //动态链接库初始化
        #region=========LEDSender2010.dll===========
        //设备通讯参数
        public struct TDeviceParam
        {
            public ushort devType;
            public ushort comSpeed;
            public ushort comPort;
            public ushort comFlow;
            public ushort locPort;
            public ushort rmtPort;
            public ushort srcAddr;
            public ushort dstAddr;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
            public String rmtHost;
            public uint txTimeo;   //发送后等待应答时间 ====超时时间应为txTimeo*txRepeat
            public uint txRepeat;  //失败重发次数
            public uint txMovewin; //划动窗口
            public uint key;       //通讯密钥
            public int pkpLength;  //数据包大小

        }

        //设备控制参数
        public struct TSenderParam
        {
            public TDeviceParam devParam;
            public UInt32 wmHandle;
            public UInt32 wmMessage;
            public UInt32 wmLParam;
            public UInt32 notifyMode;
        }
        [DllImport("kernel32.dll")]
        private extern static IntPtr LoadLibrary(String path);

        [DllImport("kernel32.dll")]
        private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);

        [DllImport("kernel32.dll")]
        private extern static bool FreeLibrary(IntPtr lib);

        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Startup();

        //动态链接库销毁
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Cleanup();

        //创建控制卡在线监听服务
        //  serverindex 控制卡在线监听服务编号(可以在多个socket udp端口监听)
        //  localport 本地端口
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Report_CreateServer(Int32 serverindex, Int32 localport);

        //删除控制卡在线监听服务
        //  serverindex 控制卡在线监听服务编号
        [DllImport("LEDSender2010.dll")]
        public static extern void LED_Report_RemoveServer(Int32 serverindex);

        //删除全部控制卡在线监听服务
        [DllImport("LEDSender2010.dll")]
        public static extern void LED_Report_RemoveAllServer();

        //获得控制卡在线列表
        //必须先创建控制卡在线监听服务，即调用LED_Report_CreateServer后使用，否则返回值无效
        //  serverindex 控制卡在线监听服务编号
        //  plist 输出在线列表的用户外部缓冲区，
        //        如果传入空(NULL/0)，则输出到动态链接库内部的缓冲区，继续调用下面的接口取得详细信息
        //  count 最大读取个数
        //--返回值-- 小于0表示失败(未创建该在线监听服务)，大于等于0表示在线的控制卡数量
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Report_GetOnlineList(Int32 serverindex, Int32 listaddr, Int32 count);

        //获得某个在线控制卡的上报控制卡名称
        //必须先创建控制卡在线监听服务，即调用LED_Report_CreateServer后使用，否则返回值无效
        //  serverindex 控制卡在线监听服务编号
        //  itemindex 该监听服务的在线列表中，在线控制卡的编号
        //--返回值-- 在线控制卡的上报控制卡名称
        [DllImport("LEDSender2010.dll")]
        public static extern String LED_Report_GetOnlineItemName(Int32 serverindex, Int32 itemindex);

        //获得某个在线控制卡的上报控制卡IP地址
        //必须先创建控制卡在线监听服务，即调用LED_Report_CreateServer后使用，否则返回值无效
        //  serverindex 控制卡在线监听服务编号
        //  itemindex 该监听服务的在线列表中，在线控制卡的编号
        //--返回值-- 在线控制卡的IP地址
        [DllImport("LEDSender2010.dll")]
        public static extern String LED_Report_GetOnlineItemHost(Int32 serverindex, Int32 itemindex);

        //获得某个在线控制卡的上报控制卡远程UDP端口号
        //必须先创建控制卡在线监听服务，即调用LED_Report_CreateServer后使用，否则返回值无效
        //  serverindex 控制卡在线监听服务编号
        //  itemindex 该监听服务的在线列表中，在线控制卡的编号
        //--返回值-- 在线控制卡的远程UDP端口号
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Report_GetOnlineItemPort(Int32 serverindex, Int32 itemindex);

        //获得某个在线控制卡的上报控制卡地址
        //必须先创建控制卡在线监听服务，即调用LED_Report_CreateServer后使用，否则返回值无效
        //  serverindex 控制卡在线监听服务编号
        //  itemindex 该监听服务的在线列表中，在线控制卡的编号
        //--返回值-- 在线控制卡的硬件地址
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Report_GetOnlineItemAddr(Int32 serverindex, Int32 itemindex);

        //设置每次命令执行完成后，是否关闭设备。=0表示不关闭；=1表示关闭。
        [DllImport("LEDSender2010.dll")]
        public static extern void LED_CloseDeviceOnTerminate(int AValue);
        //取得控制卡IP地址
        [DllImport("LEDSender2010.dll")]
        public static extern String LED_Cache_GetBoardParam_IP();
        //取得控制卡MAC地址
        [DllImport("LEDSender2010.dll")]
        public static extern String LED_Cache_GetBoardParam_Mac();

        //取得控制卡设备地址
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Cache_GetBoardParam_Addr();

        //取得控制卡设备宽度
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Cache_GetBoardParam_Width();

        //取得控制卡设备高度
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Cache_GetBoardParam_Height();

        //取得控制卡设备亮度
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Cache_GetBoardParam_Brightness();

        //设置控制卡IP地址
        [DllImport("LEDSender2010.dll")]
        public static extern void LED_Cache_SetBoardParam_IP(String value);

        //设置控制卡MAC地址
        [DllImport("LEDSender2010.dll")]
        public static extern void LED_Cache_SetBoardParam_Mac(String value);

        //设置控制卡设备地址
        [DllImport("LEDSender2010.dll")]
        public static extern void LED_Cache_SetBoardParam_Addr(Int32 value);

        //设置控制卡设备宽度
        [DllImport("LEDSender2010.dll")]
        public static extern void LED_Cache_SetBoardParam_Width(Int32 value);

        //设置控制卡设备高度
        [DllImport("LEDSender2010.dll")]
        public static extern void LED_Cache_SetBoardParam_Height(Int32 value);

        //设置控制卡设备亮度
        [DllImport("LEDSender2010.dll")]
        public static extern void LED_Cache_SetBoardParam_Brightness(Int32 value);
        //设置控制卡参数
        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Cache_SetBoardParam(ref TSenderParam param);

        [DllImport("LEDSender2010.dll")]
        public static extern int LED_Cache_SetBoardParam2(Int32 param_index);
        #endregion
    }
}
